import cv2
from PIL import Image
import glob


# video_file = "/home/daybeha/Downloads/cells.mp4"

file_path = "/home/daybeha/Downloads/"
# file_name = "cells.mp4"
file_name = "yolo_mask.mp4"
outfile_name = file_name.split('.')[0] + ".gif"
# 读取视频文件
cap = cv2.VideoCapture(file_path + file_name)

# # 设置截取范围
# start_frame = 100
# end_frame = 2800
#
# sample_rate = 50 # 每隔 50 帧采样

start_frame = 0
end_frame = 80
sample_rate = 2 # 每隔 50 帧采样

frame_count = 0
frames = []


# 检查是否成功读取视频
if not cap.isOpened():
    print('Error opening video file')
    exit()




while frame_count < end_frame:
    while frame_count < start_frame:
        ret, frame = cap.read()
        frame_count += 1
    # 读取帧
    ret, frame = cap.read()

    # 检查是否读取成功
    if not ret:
        break

    # 仅在需要时保存帧
    if frame_count % sample_rate == 0:
        print(f"processing frame {frame_count} / {end_frame}")

        # 显示帧
        cv2.imshow('Video', frame)

        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        image = Image.fromarray(frame)
        frames.append(image)
        # 等待按键事件
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
        # cv2.imwrite(output_path + f"imgs/frame_{frame_count:03d}.jpg", frame)
    # 更新帧计数器
    frame_count += 1

# 释放资源
cap.release()
cv2.destroyAllWindows()



# # 读取目录下图片，用Pillow模块的Image和所有图片合并
# # 成一张gif
# images = glob.glob(output_path + f"imgs/*.jpg")
# images.sort()
# frames = [Image.open(image) for image in images]
frame_one = frames[0]
frame_one.save(file_path + outfile_name, format="GIF", append_images=frames[1:],
               save_all=True, duration=40, loop=0)
